function loadPage(sourceDiv, actionURL, serviceId) {	
		
	$.ajax ({		
		url:	  	actionURL + "?set_ajax_view",
		data:		"service_id=" + serviceId,		
		dataType: 	"html",
		beforeSend: function() {					
			$('div#testListContent').hide();	
			$('div#pageContent').hide();
			$('div#' + sourceDiv).hide();			
		},
		complete: 	function() {
			$('div#' + sourceDiv).show();			
		},
		success:  function(data) {
			$("#" + sourceDiv).html(data);			
		}
	});		
}

////////////// LIST SERVICE by DEPARTMENT ///////////////////
function listTestItem() {
	$('#current_dept').text($('#departmentList :selected').attr('label'));	
	$.ajax ({		
		url:	  	"ListTestItemAjax?set_ajax_view",
		dataType: 	"json",
		success:  function(data) {
			serviceTable = $('#test_item_list');
			fillTableData(serviceTable, data.body);
			fillTotalTableData($('#service_container'), data.total);	
			
			if ($('tbody tr', serviceTable).length > 0) {
				$("#pagination").show();
				serviceTable.trigger("update");																			
				serviceTable.tablesorterPager({
					container: $("#pagination"),
					size: 10,										
					positionFixed: false
				});
			} else {
				$("#pagination").hide();
			}								
			$('#service_container').show();		
		}
	});	
}

////////////// FILL DATA and STYLE SERVICE TABLE ///////////////////
function fillTotalTableData(parentDiv, data) {
	$('table.total_table', parentDiv).remove();
	parentDiv.append(data);
	parentDiv.children('table:last-child').addClass('total_table');
}

function fillTableData(table, data) {
	$('tbody', table).children().remove();	
	$('tbody', table).append(data);		
}

////////////// LOCK AND UNLOCK A SERVICE ///////////////////
function lockService(serviceId) {
	var message = _('Are you sure to temporary lock <span class=\"impression\">{0}</span> service?',$('#service_list tr#' + serviceId + ' td:nth-child(2)').text())
		+ _('<span class=\"impression\">Notice:</span> When registering a new ticket, receptionist will not see this service'); 
	show(message, serviceId, 'lock');
}

function unlockService(serviceId) {
	var message = _('Are you sure to unlock the <span class="impression">{0}</span> service?', $('#service_list tr#' + serviceId + ' td:nth-child(2)').text());
	 show(message, serviceId, 'unlock');
}

function show(message, serviceId, control) {
	promptConfirm('',message, function() {
		submitChangeServiceStatus(serviceId, control);
		return true;
	},'OkCancel','',_('Cancel'));
}

function submitChangeServiceStatus(serviceId, control) {
	$.ajax ({	
		url:	  	"ChangeServiceStatusAjax?set_ajax_view",
		data:		"service_id=" + serviceId,		
		beforeSend: function() {				
			$('div#search_button').hide();					
			$('div#barLoading').show();			
		},
		complete: 	function() {			
			$('div#barLoading').hide();
			$('div#search_button').show();
		},
		success:  function(data) {
			serviceTable = $('#test_item_list');
			var html = '';
			var status = '';
			if (control == 'lock') {
				status = '<span class="impression">' + _("Temporary lock") + '</span>';
				html = '<a class="btn" href="javascript:unlockService(' + serviceId + ');" title="' + _("Unlock service") + '">' 
				+ '<img src="../images/unlock_small.png" alt="Unlock"></img></a>'; 				
			} else if (control == 'unlock') {
				status = '<span>' + _("In use") + '</span>';
				html = '<a class="btn" href="javascript:lockService(' + serviceId + ');" title="'+ _("Temporary lock service") + '">' 
				+ '<img src="../images/lock_small.png" alt="Temporary lock"></img></a>'; 				
			}
			$('tr#'+serviceId + ' td:nth-child(8)', serviceTable).html(status);
			$('tr#'+serviceId + ' a.btn', serviceTable).parent().html(html);
											
		}
	});	
}

////////////////// ADD-REMOVE ROOMS /////////////////
var roomArray = new Array();
function addRoom() {
	var roomId = $('#room :selected').val();
	var roomName = $('#room :selected').attr('label');
		
	if ($.inArray(roomId, roomArray) >= 0) {		
		generalDialog(null,null,_('Existed <span class="impression">{0}</span>',roomName),'warn');
		return;
	}	
	
	var html =
		'<tr id="' + roomId + '"><td><input type="hidden" value="' + roomId + '" name="roomId[]">'
			+ ' <span>' + roomName + '</span>	</td>'
			+ '<td> <a href="javascript:removeRoom(' + roomId + ');" title="' + _("Delete room") + '">' 
			 		+ '<img src="../images/remove_small.png" alt="'+ _("Delete") + '"></img>' 
			+ '</a></td></tr>';
	$('tbody', $('#room_list')).append(html);
	roomArray.push(roomId);
		
	$('#room_list tr').removeClass('alt');
	$('#room_list tr:even').addClass('alt');
	$('#room_list').show();
		
}

function removeRoom(roomId) {
	$('#room_list tr#' + roomId).nextAll().toggleClass('alt');
	$('#room_list tr#' + roomId).remove();
	roomArray.pop(roomId);
	if ($('#room_list tbody tr').length == 0) {
		$('#room_list').hide('medium'); 
	} 
}


/////////////////// SAVE TEST ITEM ////////////
function saveTestItem() {
	var res = isReadyToSubmit();
	if (res == false) {
		return ;
	}
	var submitData = $('#add_service_form').formSerialize();
	var serviceId = $('#service_id').val(); 
	$.ajax ({
			type:   "POST",
			url:	"SaveTestItemAjax?set_ajax_view",
			data:	submitData,
			beforeSend: function() {
				$('#btn_save').hide();
				$('#barLoading').show();				
			},
			complete: 	function() {
				$('#btn_save').show();
				$('#barLoading').hide();
			},
			success:	function(data) {
				$('div#pageContent').hide('slow');
				listTestItem();
				$('div#testListContent').show();
			}
		});
}

function editTestItem(serviceId) {
	$('div#testListContent').hide();
	loadPage('pageContent', 'EditTestItem', serviceId);
}
// Load a page to edit a specified test or create a new test
function editTest(testId) {
    $('div#testListContent').hide();
    // call ajax to load page
    loadPage('pageContent', 'EditTest', testId);
}

// Save group test
function saveGroupTest() {
    // check group_test_name
    if (!isNotEmpty($('#group_test_name'), _("Empty diagnosis type"), "status_message")) {
        return;
    }
    // check room of group test
    if (!isNotEmpty($('#room'), _("Empty room"), "status_message")) {
        return;
    }
    // check payment_type of group test
    if (!isNotEmpty($('#payment_type'), _("Empty payment type"), "status_message")) {
        return;
    }
    
    var submitData = $('#add_group_test_form').formSerialize();
    $.ajax ({
            type:   "POST",
            url:    "SaveGroupTestAjax?set_ajax_view",
            data:   submitData,
            beforeSend: function() {
                $('#btn_save').hide();
                $('#barLoading').show();                
            },
            complete:   function() {
                $('#btn_save').show();
                $('#barLoading').hide();
            },
            success:    function(data) {
                $('div#pageContent').hide('slow');
                loadPage('testListContent', 'ListTest', '');
                $('div#testListContent').show();
            }
        });
}

////////////////// LOCK AND UNLOCK TEST /////////////////////
//@testId: The id of the specified test be locked or unlocked
//@control: The status of test ('lock', 'unlock')
function changeGroupTestStatus(testId, control) {
    $.ajax ({   
        url:        "ChangeGroupTestStatusAjax?set_ajax_view",
        data:       "test_id=" + testId,
        success:  function(data) {
            testTable = $('#test_list');
            var html = '';
            var status = '';
            if (control == 'lock') {
                status = '<span class="impression">' + _("Temporary lock") + '</span>';
                html = '<a class="btn" href="javascript:changeGroupTestStatus(' + testId + ', \'unlock\');" title="' + _("Unlock service") + '">' 
                + '<img src="../images/unlock_small.png" alt="' + _("Unlock") + '"></img></a>';
            } else if (control == 'unlock') {
                status = '<span>' + _("In use") + '</span>';
                html = '<a class="btn" href="javascript:changeGroupTestStatus(' + testId + ', \'lock\');" title="' + _("Temporary lock service") + '">' 
                + '<img src="../images/lock_small.png" alt="' + _("Temporary lock") + '"></img></a>';
            }
            $('tr#'+ testId + ' td:nth-child(4)', testTable).html(status);
            $('tr#'+ testId + ' a.btn', testTable).parent().html(html);
        }
    });
}

function isReadyToSubmit() {
	
	if (!isNotEmpty($('#service_name'), _("Empty service name"), "status_message")) {
		return false;
	}		
	
	if (!isNotEmpty($('#price'), _("Empty service price"), "status_message")) {
		return false;
	}
	
	if (!checkNumber($('#price'), _("Invalid service price"), "status_message", "#AAA")) {
		return false;
	} 
		 
	if (!checkNumber($('#required_insurance_price'), _("Invalid required insurance price"), "status_message", "#AAA")) {
		return false;
	}		

	if (!checkNumber($('#volunteered_insurance_price'), _("Invalid volunteered insurance price"), "status_message", "#AAA")) {
		return false;
	}
		
	return true;
}